﻿using System;
using System.IO;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters;

namespace netCoreStudy.Extensions
{
	public static class SwaggerSetup
	{
		public static void AddSwaggerSetup(this IServiceCollection services)
		{
			if (services == null)
				throw new ArgumentNullException(
					nameof(services)
				);
			services.AddSwaggerGen(c =>
			{
				c.SwaggerDoc("v1", new OpenApiInfo
					{
						Version = "v1",
						Title = "Api接口文档"
					}
				);

				// Assembly.GetExecutingAssembly().GetName().Name 为获取 当前 程序集名称 
				c.IncludeXmlComments(
					$"{Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml")}",
					true
				);
				// 配置小锁标记 
				// 配置jwt 授权认证 
				c.OperationFilter<AddResponseHeadersFilter>();
				c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();

				// 给请求 前面 加上 bearer 过滤 
				c.OperationFilter<SecurityRequirementsOperationFilter>();

				// Jwt Bearer 认证，必须是 oauth2
				c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme()
				{
					Description = "JWT授权(数据将在请求头中进行传输) 直接在下框着输入Bearer {token}(注意两者中间是一个空格)\"",
					Name = "Authorization", //jwt 默认参数名称 
					In = ParameterLocation.Header, //jwt 默认存在 authorization 信息 的位置 (请求头中 header)
					Type = SecuritySchemeType.ApiKey
				});
			});
		}
	}
}